import React from 'react';
import PropTypes from 'prop-types';
import {cloneDeep, get} from 'lodash';
import {FormattedMessage} from 'react-intl';
import {AppIcon, IfPermission} from '@folio/stripes/core';

import {Button, expandAllFunction, HasCommand, LoadingPane, Pane, PaneMenu} from '@folio/stripes/components';

import ConfirmationModal from '@folio/stripes-components/lib/ConfirmationModal';

import {BookInStorageInfo} from '../../components/DetailSections';

import HelperApp from '../../components/HelperApp';

import {BASE_PAHT} from '../../constants';

class BooInStorageDetail extends React.Component {
  static propTypes = {
    stripes: PropTypes.shape({
      hasPerm: PropTypes.func.isRequired,
      connect: PropTypes.func.isRequired,
      locale: PropTypes.string.isRequired,
      logger: PropTypes.shape({
        log: PropTypes.func.isRequired,
      }).isRequired,
    }).isRequired,
    resources: PropTypes.shape({
      selBookInStorage: PropTypes.object,
      bookInStorage: PropTypes.arrayOf(PropTypes.object),
      settings: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
    }),
    match: PropTypes.shape({
      path: PropTypes.string.isRequired,
      params: PropTypes.shape({
        id: PropTypes.string,
      }),
    }).isRequired,
    onClose: PropTypes.func,
    location: PropTypes.object,
    history: PropTypes.object,
    paneWidth: PropTypes.string,
  };

  static defaultProps = {
    paneWidth: '44%'
  };

  constructor(props) {
    super(props);

    this.editButton = React.createRef();

    this.keyboardCommands = [
      {
        name: 'edit',
        handler: this.goToEdit,
      },
      {
        name: 'collapseAllSections',
        handler: this.collapseAllSections,
      },
      {
        name: 'expandAllSections',
        handler: this.expandAllSections,
      },
    ];

    this.state = {
      lastUpdate: null,
    };
  }

  getBookInStorage = () => {
    const { resources, match: { params: { id } } } = this.props;
    const selBookInStorage = (resources.selBookInStorage || {}).records || [];

    if (selBookInStorage.length === 0 || !id) return null;
    // Logging below shows this DOES sometimes find the wrong record. But why?
    // console.log(`getUser: found ${selUser.length} users, id '${selUser[0].id}' ${selUser[0].id === id ? '==' : '!='} '${id}'`);
    return selBookInStorage.find(u => u.id === id);
  }

  checkScope = () => {
    return document.getElementById('ModuleContainer').contains(document.activeElement);
  };

  // This is a helper function for the "last updated" date element. Since the
  // date/time is actually set on the server when the record is updated, the
  // lastUpdated element of the record on the client side might contain a stale
  // value. If so, this returns a locally stored update date until the data
  // is refreshed.
  dateLastUpdated(bookInStorage) {
    const updatedDateRec = get(bookInStorage, ['updatedDate'], '');
    const updatedDateLocal = this.state.lastUpdate;

    if (!updatedDateRec) { return ''; }

    let dateToShow;
    if (updatedDateLocal && updatedDateLocal > updatedDateRec) {
      dateToShow = updatedDateLocal;
    } else {
      dateToShow = updatedDateRec;
    }

    return new Date(dateToShow).toLocaleString(this.props.stripes.locale);
  }

  showHelperApp = (helperName) => {
    this.setState({
      helperApp: helperName
    });
  }

  closeHelperApp = () => {
    this.setState({
      helperApp: null
    });
  }

  handleExpandAll = (obj) => {
    this.setState((curState) => {
      const newState = cloneDeep(curState);
      newState.sections = obj;
      return newState;
    });
  }

  handleSectionToggle = ({ id }) => {
    this.setState((curState) => {
      const newState = cloneDeep(curState);
      newState.sections[id] = !newState.sections[id];
      return newState;
    });
  }

  toggleAllSections = (expand) => {
    this.setState((curState) => {
      const newSections = expandAllFunction(curState.sections, expand);
      return {
        sections: newSections
      };
    });
  }

  expandAllSections = (e) => {
    e.preventDefault();
    this.toggleAllSections(true);
  }

  collapseAllSections = (e) => {
    e.preventDefault();
    this.toggleAllSections(false);
  }

  // focus management when edit layer closes (refocus edit button)
  afterCloseEdit = () => {
    if (this.editButton.current) {
      this.editButton.current.focus();
    }
  };

  getEditLink = () => {
    const {
      match: { params },
      location: { search }
    } = this.props;

    return `${BASE_PAHT}/${params.id}/edit${search}`;
  }

  onClose = () => {
    const {
      history,
      location
    } = this.props;

    history.push(`${BASE_PAHT}${location.search}`);
  }

  renderDetailMenu(bookInStorage) {
    return (
      <>
        <PaneMenu>
          <IfPermission perm="ui-book-in-storage.edit">
            <FormattedMessage id="ui-users.crud.editUser">
              {ariaLabel => (bookInStorage &&
              <Button
                id="clickable-editBookInStorage"
                buttonStyle="primary"
                to={this.getEditLink()}
                buttonRef={this.editButton}
                aria-label={ariaLabel}
                marginBottom0
              >
                    编辑
              </Button>
              )}
            </FormattedMessage>
          </IfPermission>
          <Button
            id="bt-submited"
            buttonStyle="primary"
            onClick={this.onSubmited}
            marginBottom0
          >
            送审
          </Button>
        </PaneMenu>
      </>
    );
  }

  getActionMenu = barcode => ({ onToggle }) => {
    const showActionMenu = this.props.stripes.hasPerm('ui-book-in-storage.edit');

    if (showActionMenu) {
      return (
        <>
          <IfPermission perm="ui-users.edit">
            <Button
              buttonStyle="dropdownItem"
              data-test-actions-menu-edit
              id="clickable-editBookInStorage"
              onClick={() => {
                onToggle();
                this.goToEdit();
              }}
              buttonRef={this.editButton}
            >
              <Icon icon="edit">
                编辑
              </Icon>
            </Button>
          </IfPermission>
        </>
      );
    } else {
      return null;
    }
  }

  checkScope = () => true;

  goToEdit = () => {
    const { history, match: { params } } = this.props;
    history.push(`${BASE_PAHT}/${params.id}/edit`);
  }

  onSubmited = () => {
    // <ConfirmationModal
    //   open
    //   id="confirmation-onsubmited"
    //   heading="确认"
    //   message="是否确认送审"
    //   bodyTag="div"
    //   onConfirm={alert('Confirmed')}
    //   onCancel={alert('Cancelled')}
    //   cancelLabel="取消"
    //   confirmLabel="确定"
    // />;

    alert('onSubmited');

    const {
      mutator,
      history,
      match: { params },
      location: {
        state,
        search,
      },
    } = this.props;


    mutator.submitBookInStorage.POST({id:params.id}).then(() => {
      history.push({
        pathname: params.id ? `${BASE_PAHT}/preview/${params.id}` : '${BASE_PAHT}',
        search,
        state,
      });
    });
  }

  shortcuts = [
    {
      name: 'edit',
      handler: this.goToEdit,
    },
    {
      name: 'expandAllSections',
      handler: this.expandAllSections,
    },
    {
      name: 'collapseAllSections',
      handler: this.collapseAllSections
    }
  ]

  render() {
    const {
      resources,
      stripes,
      location,
      match,
      onClose,
      paneWidth,
    } = this.props;

    const {
      sections,
      helperApp,
      addRecord
    } = this.state;

    const bookInStorage = this.getBookInStorage();

    const detailMenu = this.renderDetailMenu(bookInStorage);

    if (!bookInStorage) {
      return (
        <LoadingPane
          id="pane-bookinstorage-details"
          defaultWidth={paneWidth}
          paneTitle="馆藏入库详细信息"
          dismissible
          onClose={onClose}
        />
      );
    } else {
      return (
        <HasCommand
          commands={this.shortcuts}
          isWithinScope={this.checkScope}
          scope={document.body}
        >
          <>
            <Pane
              data-test-instance-details
              id="pane-bookinstoragedetails"
              appIcon={<AppIcon app="book-in-storage" appIconKey="book-in-storage" />}
              defaultWidth={paneWidth}
              lastMenu={detailMenu}
              dismissible
              onClose={this.onClose}
            >

              <BookInStorageInfo stripes={stripes} bookInStorage={bookInStorage} />

            </Pane>
            { helperApp && <HelperApp appName={helperApp} onClose={this.closeHelperApp} /> }
          </>
        </HasCommand>
      );
    }
  }
}

export default BooInStorageDetail;
